package com.nwu.user.service.impl;



import com.nwu.user.domain.User;
import com.nwu.user.domain.dto.LoginDto;
import com.nwu.user.domain.po.LoginUser;
import com.nwu.user.mapper.LoginMapper;
import com.nwu.user.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public User login(LoginDto loginDto) {
        //用authenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getUsername(),loginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate == null){
            throw new RuntimeException("用户找不到");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        return loginUser.getUser();
    }

    @Override
    public List<String> getRoleById(Long id) {
        return loginMapper.getRoleById(id);
    }


}
